//首页
import React, { useEffect, useRef, useState } from 'react';
import {
  Button,
  Image,
  RichText,
  ScrollView,
  Text,
  View,
} from '@tarojs/components';
import { HtmlView } from 'taro-html-view';
import './index.less';
import Taro, {
  useDidShow,
  usePageScroll,
  useRouter,
  useShareAppMessage,
} from '@tarojs/taro';
import store from '@/src/store';
import CommonModal from '@/src/components/commonModal';
import { AtInput } from 'taro-ui';
import classNames from 'classnames';
import TitleBar from '@/src/components/titleBar';
import { getDetailFun, signUpFun } from '@/src/common/method/activityFun';
import LoadingSpinner from '@/src/components/loadingSpinner';
import { observer } from 'mobx-react-lite';
import progressIcon from '../../assert/activity/progress.png';
import { formatRichText } from '@/src/common/util/util';
import { netWorkErrorInfo } from '@/src/utils/constants';
import { isLoginFun } from '@/src/common/method/commonFun';

// 定义路由参数接口
interface RouteParams {
  activityId: string;
  showBtn?: boolean;
  customParam?: boolean;
  userId: string;
  param?: string;
}
//活动详情
const Detail = () => {
  const { params } = useRouter<RouteParams>();
  const [showJoinModal, setShowJoinModel] = useState<boolean>(false); //是否展示弹框
  const [name, setName] = useState<string>(''); //姓名
  const [mobile, setMobile] = useState<any>(''); //手机号
  const [remark, setRemark] = useState<string>(''); //备注
  const [bgColorWhite, setBgColorWhite] = useState<boolean>(false); //设备header背景是否为白色
  const [modalTitle, setModalTitle] = useState('报名信息填写');
  const [signUp, setSignUp] = useState<boolean>(false); //是否报名成功
  const [submitBtn, setSubmitBtn] = useState<boolean>(false); //是否填写用户名和手机号
  const [item, setItem] = useState<any>([]);
  const [loadingText, setLoadingText] = useState<any>('加载中...');
  const [clickable, setClickable] = useState<boolean>(true);
  const pixelRatioRef = useRef(1);
  const thresholdRef = useRef(10); // 默认阈值50dip
  const lastScrollTop = useRef(0); // 使用ref记录上一次滚动位置
  const [scrollDirection, setScrollDirection] = useState('');
  const wrapperCls = ['sign-up', submitBtn ? 'writtable' : 'nowrittable'];
  let top = `calc(${store.commonStore.safeAreaTop}rpx + 278rpx)`;
  const shareData = {
    customParam: 'share',
    userId: '88888888',
  };
  const activityList: any = {
    0: '报名结束',
    1: '报名中',
    2: '进行中',
    3: '已结束',
    4: '活动终止',
  };
  useEffect(() => {
    const sysInfo = Taro.getSystemInfoSync();
    pixelRatioRef.current = sysInfo.pixelRatio;
    const screenHeight = sysInfo.screenHeight;
    thresholdRef.current = screenHeight * 0.01; // 屏幕高度的10%
    if (store.commonStore.networkStatus) {
      //如果是分享出去的页面，userId传固定的88888888
      getDetailFun({
        activityId: params.activityId,
        userId: Taro.getStorageSync('userId')
          ? Taro.getStorageSync('userId')
          : '88888888',
      }).then((res: any) => {
        setLoadingText('');
        setItem(res);
        if (
          ((String(res.activityStatus) === '2' && !res.hasSignUp) ||
            (String(res.activityStatus) === '0' && !res.hasSignUp) ||
            String(res.activityStatus) === '4') &&
          params.param !== 'share'
        ) {
          setClickable(false);
        }
      });
    } else {
      Taro.showToast({
        title: netWorkErrorInfo,
        icon: 'none',
      });
    }
  }, []);

  const handleChange = (val: any, type: any) => {
    if (type === 'name') {
      //限制只能输入10个字
      if (val.length > 10) {
        Taro.showToast({ title: '名字最多输入10个字', icon: 'none' });
        return;
      } else {
        setName(val);
      }
    } else if (type === 'mobile') {
      setMobile(val);
    } else if (type === 'remark') {
      if (val.length < 20) {
        setRemark(val);
      } else {
        setRemark(val.slice(0, 20));
        Taro.showToast({ title: '备注最多20个字符', icon: 'none' });
      }
    }
    if (name !== '' && mobile.length === 11) {
      setSubmitBtn(true);
    }
    return val;
  };

  //报名方法
  const joinFun = () => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    //判断用户是否登录
    if (!isLoginFun()) return;
    //报名中状态并且还没报名
    if (
      activityList[item.activityStatus] === '报名中' &&
      item.hasSignUp === false
    ) {
      setShowJoinModel(true);
      //活动已结束，并且有活动回顾
    } else if (activityList[item.activityStatus] === '已结束') {
      //跳转到活动回顾页面
      Taro.navigateTo({
        url: `/subPagesActivity/review/index?activityId=${params.activityId}`,
      });
    }
  };

  //提交报名
  const submitJoin = () => {
    if (!name || name.trim() === '') {
      Taro.showToast({ title: '请输入姓名', icon: 'none' });
      return;
    }
    if (!mobile) {
      Taro.showToast({ title: '请输入手机号码', icon: 'none' });
      return;
    }
    if (mobile.length !== 11) {
      Taro.showToast({ title: '请输入正确手机号码', icon: 'none' });
      return;
    }
    //调用接口处理逻辑
    signUpFun({
      activityId: params.activityId,
      userId: Taro.getStorageSync('userId'),
      userPhone: Taro.getStorageSync('mobile'),
      applicantName: name,
      applicantPhone: mobile,
      remark: remark,
    })
      .then((res: any) => {
        console.log(res, '返回成功====');
        if (res.code === '0') {
          setSignUp(true);
          setModalTitle('报名已提交');
          if (signUp) {
            setShowJoinModel(false);
          }
        } else {
          Taro.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      })
      .catch((e: any) => {
        console.log(e, '报名失败');
      });
  };

  //报名信息弹框
  const content = () => {
    return (
      <View className="activity-detail-modal">
        {signUp ? (
          <View>可以在「我的—我的活动」中查看报名信息。</View>
        ) : (
          <>
            <AtInput
              name="name"
              title="姓名"
              type="text"
              placeholderClass="custom-placeholder"
              placeholder="请输入姓名"
              value={name}
              onChange={(val: any) => handleChange(val, 'name')}
            />
            <AtInput
              name="mobile"
              title="手机号"
              type="number"
              maxLength={11}
              placeholder="请输入手机号"
              value={mobile}
              onChange={(val: any) => handleChange(val, 'mobile')}
            />
            <AtInput
              name="remark"
              title="备注"
              type="text"
              placeholder="请输入备注信息"
              value={remark}
              onChange={(val: any) => handleChange(val, 'remark')}
            />
          </>
        )}
      </View>
    );
  };
  //滚动方法
  const handleScroll = () => {
    setBgColorWhite(true);
  };
  console.warn(bgColorWhite, 'bgColorWhite========');
  //页面向下滚动
  usePageScroll((res: any) => {
    const currentScrollTop = res.scrollTop;
    if (currentScrollTop > lastScrollTop.current) {
      console.log('向下滑动');
      //如果滑动到
      setScrollDirection('DOWN');

      // 执行下滑操作
    } else if (currentScrollTop < lastScrollTop.current) {
      console.log('向上滑动');
      // 执行上滑操作
      setScrollDirection('UP');
    }

    // 更新滚动位置
    lastScrollTop.current = currentScrollTop;
  });

  useDidShow(() => {
    console.error(params.param, 'fromShare========');
  });

  useShareAppMessage((res: any) => {
    if (res.from === 'button') {
      const { customParam, userId } = res.target.dataset;
      console.log('分享按钮携带的参数:', customParam, userId);

      return {
        path: `/subPagesActivity/detail/index?param=${customParam}&activityId=${encodeURIComponent(params.activityId)}&showBtn=true&userId=${userId}`,
      };
    }

    return {
      path: `/subPagesActivity/detail/index?activityId=${params.activityId}&showBtn=true`,
    };
  });
  //返回
  const handleBack = () => {
    //判断用户是否登录
    if (!isLoginFun()) return;
    Taro.navigateBack()
      .then((res: any) => {
        console.log(res, '返回成功啦');
      })
      .catch((e: any) => {
        console.log(e, '返回失败');
        Taro.switchTab({ url: '/pages/home/index' });
      });
  };
  return (
    <View
      className="activity-detail-container"
      // style={{ height: `calc(100vh - ${store.commonStore.pageAreaTop}rpx)` }}
    >
      <ScrollView
        className="activity-detail-scroll"
        scrollY
        scrollWithAnimation
        upperThreshold={Number(top)}
        enableBackToTop
        onScrollToUpper={() => setBgColorWhite(false)}
        onScroll={() => handleScroll()}
      >
        <View
          className="activity-detail-banner"
          style={{
            height: `calc(${store.commonStore.safeAreaTop}rpx + 278rpx)`,
            paddingTop: `${store.commonStore.safeAreaTop}rpx`,
          }}
        >
          <View
            className="banner-bg"
            style={{
              height: `calc(${store.commonStore.safeAreaTop}rpx + 278rpx)`,
              paddingTop: `${store.commonStore.safeAreaTop}rpx`,
              backgroundColor: '#000',
              filter: 'blur(0px)',
            }}
          ></View>
          <View
            className="banner-bg"
            style={{
              height: `calc(${store.commonStore.safeAreaTop}rpx + 278rpx)`,
              paddingTop: `${store.commonStore.safeAreaTop}rpx`,
              backgroundImage: `url(${item.coverImageUrl})`,
            }}
          ></View>
          {bgColorWhite ? (
            <TitleBar showLeftBack={true} title={item.title}></TitleBar>
          ) : (
            <View className="activity-detail-navbar">
              <Image
                className="tb-back"
                onClick={() => handleBack()}
                src={
                  'https://file.linkcook.cn/image/wineMiniProgram/activity/back-white.png'
                }
              />
            </View>
          )}
          {/* 海报和名称部分 */}
          <View
            className="activity-detail-poster"
            style={{
              marginTop: bgColorWhite ? '7vh' : '0',
            }}
          >
            <View className="activity-detail-poster-left">
              <Image src={item.coverImageUrl} />
            </View>
            <View className="activity-detail-poster-right">
              <View
                className="activity-detail-poster-title"
                style={{ height: bgColorWhite ? '100rpx' : '100rpx' }}
              >
                {item.title}
              </View>
              <View className="activity-detail-poster-limit">
                .{item.activityType}.
              </View>
              <View className="activity-detail-poster-time">
                <Text className="activity-detail-poster-time-text">
                  {activityList[item.activityStatus]}
                </Text>
                {item.registrationEndTime &&
                  item.registrationEndTime.split(' ')[0]}{' '}
                截止
              </View>
              <View className="activity-detail-poster-price">
                入场费：<Text className="money">{item.activityCost}</Text>
                元/位
              </View>
            </View>
          </View>
        </View>

        {/* 可以滑动的部分 */}
        <View style={{ marginTop: bgColorWhite ? '56px' : '56px' }}>
          {/* 活动时间 */}
          <View className="activity-detail-period common-container">
            <View className="activity-detail-time">
              <Image
                src={
                  'https://file.linkcook.cn/image/wineMiniProgram/activity/position.png'
                }
                className="iconAddress"
              />
              活动时间：
            </View>

            <View className="activity-detail-start-end">
              {item.activityTimes}
            </View>
          </View>
          {/* 活动地点 */}
          <View className="activity-detail-period common-container">
            <View className="activity-detail-time">
              <Image
                src={
                  'https://file.linkcook.cn/image/wineMiniProgram/activity/position.png'
                }
                className="iconAddress"
              />
              活动地点：
            </View>

            <View className="activity-detail-start-end">
              <View className="activity-detail-address">
                {item.activityAddress}
              </View>
              {/* 暂时屏蔽掉此功能 */}
              {/* <View
                className="activity-detail-navigate"
                onClick={handleNavigate}
              ></View> */}
            </View>
          </View>
          {/* 报名进度 */}
          <View className="activity-detail-period common-container">
            <View className="activity-detail-time">
              <Image src={progressIcon} className="icon" />
              报名进度：
            </View>

            <View className="activity-detail-start-end">
              <View>活动名额：{item.maxRegistrationCount}人</View>
              <View>已报名人数：{item.actualRegistrationCount}人</View>
            </View>
          </View>
          {/* 活动详情 */}
          <View className="activity-detail-content common-container">
            <View className="title">活动详情</View>
            {/* 将富文本转为文本 */}
            <RichText nodes={formatRichText(item.introduction)}></RichText>
          </View>
          {/* 活动品鉴雪茄 */}
          {item.cigarList && (
            <View className="activity-detail-product common-container">
              <View className="title">活动品鉴雪茄</View>
              <View className="list">
                {item.cigarList &&
                  item.cigarList.map((item: any, index: any) => {
                    return (
                      <View className="common-container" key={index}>
                        <View className="name-en">{item.cigarBrandEnName}</View>
                        <View className="name-in">{item.cigarChName}</View>
                        <Image src={item.imageUrl} />
                      </View>
                    );
                  })}
              </View>
            </View>
          )}
        </View>
      </ScrollView>

      {/* <BottomContainer /> */}
      <View
        className="bottom-container"
        style={{
          height: `calc(${store.commonStore.safeAreaBottom}rpx + 112rpx)`,
          width: '100%',
        }}
      ></View>
      {/* 报名信息填写 */}
      <CommonModal
        visible={showJoinModal}
        title={modalTitle}
        className={wrapperCls}
        okText={signUp ? '' : '提交'}
        content={content()}
        okClick={submitJoin}
        cancelText={signUp ? '我知道了' : '取消'}
        cancelClick={() => setShowJoinModel(false)}
      />
      {/* 分享&报名按钮 */}
      {params.showBtn && (
        <View className="common-btn">
          <View className="common-btn-wrap">
            <Button
              className="common-btn-refuse"
              openType="share"
              data-custom-param={shareData.customParam}
              data-user-id={shareData.userId}
            >
              分享
            </Button>
            <Button
              className={classNames(
                `common-btn-agree common-btn-agree-${clickable}`
              )}
              onClick={joinFun}
            >
              {/* 
              hasSignUp：false-未报名，
              hasSignUp：true-已报名,
              已报名后状态下：
              registrationStatus为0未审核，
              registrationStatus为1审核通过，
              registrationStatus为2未审核通过，
              审核结束显示活动回顾 
              activityStatus活动状态(1：报名中，2:进行中，3：已结束，4：已终止)
              2/4状态显示立即报名置灰显示
              */}
              {Number(item.activityStatus) <= 2 && item.hasSignUp === false && (
                <Text>立即报名</Text>
              )}
              {Number(item.activityStatus) <= 2 &&
                item.hasSignUp &&
                String(item.registrationStatus) === '0' && (
                  <Text>商家审核中</Text>
                )}
              {Number(item.activityStatus) <= 2 &&
                item.hasSignUp &&
                String(item.registrationStatus) === '1' && (
                  <Text>审核通过</Text>
                )}
              {item.hasSignUp &&
                String(item.registrationStatus) === '2' &&
                Number(item.activityStatus) <= 2 && <Text>审核不通过</Text>}
              {/* {(Number(item.activityStatus) === 2 ||
                Number(item.activityStatus) === 0) &&
                !item.hasSignUp && <Text>立即报名</Text>} */}

              {String(item.activityStatus) === '3' && <Text>活动回顾</Text>}
              {String(item.activityStatus) === '4' && <Text>活动终止</Text>}
            </Button>
          </View>
        </View>
      )}
      <LoadingSpinner text={loadingText} />
    </View>
  );
};

export default observer(Detail);
